import { defineComponent, ref, reactive, h } from 'vue'
import { useFullscreen } from '@vueuse/core'
import { NModal } from 'naive-ui'
import type { Ref } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import ChapterApi from '@/service/api/yang/album/chapter'
import { NButton, NDataTable, NSpin, NPagination } from 'naive-ui'
import { useApi } from '@/hooks/useApi'
import ChapterEdit from '@/views/album/list/components/ChapterEdit'
import pageStyle from '@/theme/common.module.scss'
import MacHeader from '@/components/codeBlock/MacHeader'
import MessageBox from '@/components/nComponents/MessageBox'

export default defineComponent({
  setup(_, { expose }) {
    /**
     *  弹框属性
     * */
    const modalRef: Ref<any> = ref()
    const { isFullscreen, toggle } = useFullscreen(modalRef)
    const state: { title: string; show: boolean } = reactive({
      title: '',
      show: false
    })
    const open = (row: any): void => {
      state.title = row.name
      tableInfo.queryForm.superiorId = row.id
      queryData()
      state.show = true
    }

    const close = (): void => {
      state.show = false
    }

    expose({
      open
    })

    const handPrive = (row: any): void => {
      window.open(row.url)
    }
    const columns: DataTableColumns<any> = [
      {
        title: '章节',
        key: 'name'
      },
      {
        title: '时长',
        key: 'duration'
      },
      {
        title: '链接',
        key: 'url',
        width: 120,
        render(row) {
          return h('div', [
            h(
              NButton,
              {
                size: 'small',
                type: 'success',
                onClick: () => handPrive(row)
              },
              { default: () => '查看' }
            )
          ])
        }
      },
      {
        title: '权重',
        key: 'sort'
      },
      {
        title: '操作',
        key: 'total',
        width: 200,
        render(row, index) {
          return h('div', [
            h(
              NButton,
              {
                size: 'small',
                type: 'warning',
                class: 'ml10',
                onClick: () => handAdd(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                size: 'small',
                class: 'ml10',
                type: 'error',
                onClick: () => handDel(index)
              },
              { default: () => '删除' }
            )
          ])
        }
      }
    ]
    const addDefaultInfo: { name: string; sort: number } = reactive({
      name: '第1章',
      sort: 1
    })
    const getData = async (params: any): Promise<any> => {
      const { data } = await ChapterApi.list(params)
      if (params.pageNo === 1) {
        if (data.data.length > 0) {
          const newInfo = data.data[0]
          const cha = newInfo.name.split('第')[1].split('章')[0]
          if (cha.includes('~')) {
            const arr = cha.split('~')
            addDefaultInfo.name = `第${Number(arr.at(-1)) + 1}~章`
          } else {
            addDefaultInfo.name = `第${Number(cha) + 1}章`
          }
          addDefaultInfo.sort = newInfo.sort + 1
        } else {
          addDefaultInfo.name = '第1章'
          addDefaultInfo.sort = 1
        }
      }
      return data
    }
    const delData = async (params: any): Promise<any> => {
      return ChapterApi.dels(params)
    }
    const addRef: Ref<any> = ref()
    const {
      tableInfo,
      pageChange,
      sizeChange,
      fetchData,
      queryData,
      handAdd,
      delInfo,
      handDel,
      delConfirm
    } = useApi({
      addRef,
      getData,
      delData,
      initForm: {
        name: ''
      }
    })

    const boxSlot: { header: () => JSX.Element; default: () => JSX.Element } = {
      header: () => (
        <div>
          <div class="title">温馨提示</div>
        </div>
      ),
      default: () => (
        <>
          <div class={pageStyle.delBox}>
            <div class="pt-[10px] pb-[10px]">
              <i class="esayIcon esayIcon-jinggao"></i>
              <span class="tip">确认要删除选中数据吗?</span>
            </div>
            <div class="btns flex align-center justify-end">
              <NButton
                secondary
                onClick={() => {
                  delInfo.delShow = false
                }}
              >
                取消
              </NButton>
              <NButton style={{ marginLeft: '10px' }} type="primary" onClick={delConfirm}>
                {delInfo.delLoading && (
                  <NSpin
                    class="mr-[10px]"
                    size={15}
                    stroke="#fff"
                    v-slots={{
                      icon: () => <i class="esayIcon esayIcon-a-jiazaizhongdaxiao text-white"></i>
                    }}
                  />
                )}
                <span>确认删除</span>
              </NButton>
            </div>
          </div>
        </>
      )
    }
    return () => (
      <NModal show={state.show} onUpdateShow={close}>
        <div ref={modalRef} class={pageStyle.modalEdit} style={{ width: '800px' }}>
          <MacHeader
            title={state.title}
            is-fullscreen={isFullscreen.value}
            show-desc={false}
            onToggle={toggle}
            onClose={close}
          />
          <div class="content">
            <div class="pb20">
              <NButton
                type="success"
                onClick={() =>
                  handAdd({
                    ...addDefaultInfo,
                    superiorId: tableInfo.queryForm.superiorId
                  })
                }
              >
                <i class="esayIcon esayIcon-tianjiawenjianjia"></i>
                <span class="ml-[10px]">添加</span>
              </NButton>
            </div>
            <NDataTable
              loading={tableInfo.listLoading}
              columns={columns}
              data={tableInfo.tableData}
              pagination={false}
            />
            <div class={pageStyle.pagination}>
              <NPagination
                v-model:page={tableInfo.queryForm.pageNo}
                page-count={tableInfo.total}
                page-sizes={tableInfo.pageSizes}
                show-quick-jumper
                show-size-picker
                onUpdatePage={pageChange}
                onUpdatePageSize={sizeChange}
              />
            </div>
          </div>
          <ChapterEdit ref={addRef} onSuccess={fetchData} />
          <MessageBox width={'400px'} v-model={delInfo.delShow} isClose={false} v-slots={boxSlot} />
        </div>
      </NModal>
    )
  }
})
